package de.sinsihage.sprite;

/** Klasse GameLoopThread
 * 
 * Verwendete Android-Techniken:
 * - GameView
 * 
 * Bemerkungen:
 * 
 * 
 **/
import android.graphics.Canvas;
import android.util.Log;

public class GameLoopThread extends Thread {
	private static String TAG = "fhfl";
	static final long FPS = 10;
	private GameView view;
	private boolean running = false;

	public GameLoopThread(GameView view) {
		Log.d(TAG, "GameLoopThread");
		this.view = view;
	}

	public void setRunning(boolean run) {
		Log.d(TAG, "GameLoopThread__setRunning");
		running = run;
	}

	@Override
	public void run() {
		long ticksPS = 1000 / FPS;
		long startTime;
		long sleepTime;
		Log.d(TAG, "GameLoopThread__run()");
		while (running) {
			Log.d(TAG, "GameLoopThread__run()__while");
			Canvas c = null;
			startTime = System.currentTimeMillis();
			try {
				Log.d(TAG, "GameLoopThread__run()__while__try1");
				c = view.getHolder().lockCanvas();
				synchronized (view.getHolder()) {
					Log.d(TAG, "GameLoopThread__run()__while__try1__synchronized()");
					view.onDraw(c);
				}
			} finally {
				Log.d(TAG, "GameLoopThread__run()__while__finally1");
				if (c != null) {
					view.getHolder().unlockCanvasAndPost(c);
				}
			}
			sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
			try {
				Log.d(TAG, "GameLoopThread__run()__while__try2");
				if (sleepTime > 0)
					sleep(sleepTime);
				else
					sleep(10);
			} catch (Exception e) {
			}
		}
	}
}